<template>
  <div class="agreement app-container">
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="上架商品规则协议配置" name="1">
        <div style="border: 1px solid #ccc">
          <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="'default'" />
          <Editor
            style="height: 600px; overflow-y: hidden"
            v-model="valueHtml"
            :defaultConfig="editorConfig"
            :mode="'simple'"
            @onCreated="handleCreated"
          />
        </div>
      </el-tab-pane>
      <el-tab-pane label="商城配置" name="2">
        <h3>商城首页欢迎语</h3>
        <el-form :inline="true" :model="form" ref="formRef" class="demo-form-inline" :rules="rules" @submit.prevent>
          <el-row>
            <el-col :span="20">
              <el-form-item label="商城欢迎语" prop="info" style="width: 100%">
                <el-input
                  v-model.trim="form.info"
                  placeholder="请输入"
                  clearable
                  oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
                  maxlength="20"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <h3>商城权威标识/icon</h3>
        <el-row>
          <el-col :span="20">
            <div class="icon-list">
              <el-row :gutter="150">
                <el-col :span="12" v-for="(item, index) in iconList" :key="index">
                  <div class="icon-item mb32">
                    <div class="left">
                      <el-upload
                        class="avatar-uploader"
                        list-type="picture-card"
                        :auto-upload="false"
                        :show-file-list="false"
                        :on-change="
                          (file, fileList) => {
                            handleAvatarChangeIcon(item, file, fileList);
                          }
                        "
                      >
                        <div class="upload-wrap">
                          <template v-if="item['icon']">
                            <img :src="item['icon']" class="td-img" />
                          </template>
                          <p v-else>
                            <el-icon class="f22" style="font-weight: bold"><Plus /></el-icon>
                          </p>
                        </div>
                      </el-upload>
                    </div>
                    <div class="right">
                      <el-input
                        class="mb10"
                        placeholder="请输入名称"
                        v-model.trim="item['title']"
                        maxlength="10"
                        oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
                      ></el-input>
                      <el-input
                        class="mb10"
                        placeholder="请输入副标题"
                        v-model.trim="item['content']"
                        maxlength="20"
                        oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
                      ></el-input>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="商城定时配置" name="3">
        <h3>商品下架提醒</h3>
        <el-form
          :inline="true"
          :model="form3"
          ref="form3Ref"
          class="demo-form-inline"
          :rules="rules3"
          label-width="180"
          label-position="right"
        >
          <el-row>
            <el-col :span="20">
              <el-form-item label="商品下架提醒" prop="info1" style="width: 100%">
                <el-input
                  v-model="form3.info1"
                  placeholder="设置商品下架提醒 “ 0为没有下架 提醒，以小时为单位 ”"
                  clearable
                  type="number"
                  min="1"
                >
                  <template #suffix>
                    <span class="f12">小时</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item label="商品回收站保留删除定时" prop="info2" style="width: 100%">
                <el-input
                  v-model="form3.info2"
                  placeholder="设置商品回收定时 “ 0为立即删除，以小时为单位 ”"
                  clearable
                  type="number"
                  min="1"
                >
                  <template #suffix>
                    <span class="f12">小时</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <div class="btn-wrap">
      <el-button type="primary" @click="save">保存发布</el-button>
      <el-button type="primary" plain @click="cancel">取消</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, shallowRef, onBeforeUnmount, onMounted } from "vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import {
  getAgreementList,
  update,
  getWelcome,
  getIcons,
  getShopParams,
  updateIcons,
  updateShopParams
} from "@/api/mall/agreement";
import { getFolder, _throttle } from "@/utils/index";

const activeName = ref("1");
const formRef = ref();
const form3Ref = ref();
const form = ref({
  info: "您好！欢迎来到专业设计师选购商城~"
});
const form3 = ref({
  info1: null,
  info2: null
});
const rules = ref({
  info: [{ required: true, message: "请输入", trigger: "blur" }]
});
const rules3 = ref({
  info1: [{ required: true, message: "请输入", trigger: "blur" }],
  info2: [{ required: true, message: "请输入", trigger: "blur" }]
});
const iconList = ref([]);

onMounted(() => {
  getAgreement();
  getWelcomeFun();
  getShopParamsFun();
});

const save = () => {
  if (activeName.value === "1") {
    //协议配置
    update({ ...htmlObj.value, content: valueHtml.value, category: 1 }).then(res => {
      if (res.code === 200) {
        ElMessage({
          message: "协议配置成功",
          type: "success"
        });
        getAgreement();
      }
    });
  } else if (activeName.value === "2") {
    //商城配置
    Promise.all([updWelcome(), updIcon()])
      .then(res => {
        ElMessage({
          message: "商城配置成功",
          type: "success"
        });
        getWelcomeFun();
      })
      .catch(() => {
        ElMessage({
          message: "商城配置失败",
          type: "error"
        });
      });
  } else if (activeName.value === "3") {
    //商城定时配置
    form3Ref.value.validate((valid, fields) => {
      if (valid) {
        updateShopParams({
          ...timeObj.value,
          shopDelistTime: Number(form3.value.info1),
          delTime: Number(form3.value.info2)
        }).then(res => {
          if (res.code === 200) {
            ElMessage({
              message: "商城定时配置成功",
              type: "success"
            });
            getShopParamsFun();
          }
        });
      }
    });
  }
};

// 修改欢迎语
const updWelcome = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate((valid, fields) => {
      if (valid) {
        update({ ...welcomeObj.value, content: form.value.info, category: 6 }).then(res => {
          if (res.code === 200) {
            resolve(res.data);
          } else {
            reject("欢迎语设置失败");
          }
        });
      }
    });
  });
};

// 修改权威标识icon
const updIcon = () => {
  return new Promise((resolve, reject) => {
    const Arr = []; //有效输入icon的集合
    for (let item of iconList.value) {
      if (item.title || item.content || item.icon) {
        Arr.push(item);
      }
    }
    console.log("有效的icon输入集合===", Arr);
    updateIcons(Arr).then(res => {
      if (res.code === 200) {
        resolve(res.data);
      } else {
        reject("icon设置失败");
      }
    });
  });
};

const htmlObj = ref({}); //保存接口返回的协议内容对象
const getAgreement = () => {
  getAgreementList().then(res => {
    console.log("协议内容===", res);
    if (res.code === 200) {
      htmlObj.value = res.data[0];
      valueHtml.value = res.data[0].content;
    }
  });
};

const welcomeObj = ref({}); //保存接口返回的欢迎语对象
const getWelcomeFun = () => {
  getWelcome().then(res => {
    if (res.code === 200) {
      console.log("欢迎语===", res.data);
      welcomeObj.value = res.data[0];
      form.value.info = res.data[0].content;
    }
  });
  getIcons().then(res => {
    if (res.code === 200) {
      console.log("权威标识icon===", res.data);
      iconList.value = [];
      const ARR = JSON.parse(JSON.stringify(res.data));
      for (let i = 0; i < 5; i++) {
        if (ARR[i]) {
          iconList.value.push(ARR[i]);
        } else {
          iconList.value.push({});
        }
      }
    }
  });
};

const timeObj = ref(); //保存接口返回的下架、删除延迟时间对象
const getShopParamsFun = () => {
  getShopParams().then(res => {
    if (res.code === 200) {
      console.log("下架时间、删除时间===", res);
      timeObj.value = res.data;
      form3.value.info1 = res.data.shopDelistTime;
      form3.value.info2 = res.data.delTime;
    }
  });
};

const cancel = _throttle(() => {
  getAgreement();
  getWelcomeFun();
  getShopParamsFun();
  if (activeName.value === "3") {
    form3Ref.value.resetFields();
  } else if (activeName.value === "2") {
    formRef.value.resetFields();
  }
}, 5000);

//====================================富文本编辑器========================================================================================
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref("");
const toolbarConfig = {
  excludeKeys: ["group-image", "group-video", "emotion", "insertLink"] //配置不显示的菜单-上传图片、上传视频
  // toolbarKeys: ["bold"] //配置想要显示的菜单
};
const editorConfig = {
  placeholder: "请输入内容..."
};
const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
//====================================图片上传========================================================================================

const handleAvatarChangeIcon = (item, file, fileList) => {
  //选中文件触发的change事件
  // console.log(file);
  const isJPG = file.raw.type === "image/jpeg";
  const isPNG = file.raw.type === "image/png";
  // const isLt2M = file.raw.size / 1024 / 1024 < 0.5  //限制上传文件的大小
  if (!isPNG && !isJPG) {
    ElMessage.error("上传图片只能是 JPG/PNG 格式!");
    return false;
  } else {
    item["icon"] = URL.createObjectURL(file.raw); //赋值图片的url，用于图片回显功能
    // console.log("这里调用图片上传接口");
    customUpload(item, { file }); //调用上传文件api接口
  }
};

/**
 * 上传
 */
const customUpload = async (item, option) => {
  // 合并已上传和当前上传文件
  const folder = getFolder();
  // const objName = folder + option.file.name;
  const objName = folder + option.file.name.split(".")[0] + new Date().getTime() + "." + option.file.name.split(".")[1];

  ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("图片上传成功，地址为===", res.fileUrl);
      item["icon"] = res.fileUrl.split("?")[0];
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
</script>

<style lang="scss" scoped>
:deep(.el-upload.el-upload--picture-card) {
  width: 74px;
  height: 74px;
}
.agreement {
  position: relative;
  .btn-wrap {
    position: absolute;
    right: 20px;
    top: 20px;
  }
  .upload-wrap {
    margin-top: 3px;
    img {
      width: 72px;
      height: 72px;
      border-radius: 6px;
    }
  }
  .icon-list {
    .icon-item {
      display: flex;
      .left {
        margin-right: 10px;
      }
    }
  }
}
</style>
